﻿using Syngine.Input;

namespace Syngine.Components
{
	public abstract class Updatable : IUpdate
	{
		private UserInput _input;

		protected Updatable()
		{
			Updatables = new UpdatableList();
		}

		/// <summary>
		/// Gets or sets the input handler for this instance.
		/// </summary>
		/// <value>
		/// The input.
		/// </value>
		public UserInput Input
		{
			get
			{
				if (_input == null)
				{
					_input = new UserInput();
#if !(WINDOWS_PHONE || ANDROID)
					_input.Set(GameContext.Input.Mouse);
					_input.Set(GameContext.Input.Marquee);
					_input.Set(GameContext.Input.GamePad);
#endif
					_input.Set(GameContext.Input.Keyboard);
					_input.Set(GameContext.Input.Touch);
					_input.Initialize();
				}

				return _input;
			}
			protected set
			{
				_input = value;
			}
		}

		public bool IsInitialized { get; protected set; }

		/// <summary>
		/// Gets or sets a value indicating whether this instance is pausable.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is pausable; otherwise, <c>false</c>.
		/// </value>
		public bool IsPausable { get; set; }

		protected UpdatableList Updatables { get; private set; }

		public virtual void Initialize()
		{
			if (!IsInitialized)
			{
				IsInitialized = true;
			}
		}

		public virtual void Update(UpdateContext context)
		{
			if (IsPausable && GameState.IsPaused)
			{
				return;
			}

			Input.Update(context);
			Updatables.Update(context);
			UpdateCore(context);
		}

		protected void Add(IUpdate updatable)
		{
			Updatables.Add(updatable);
		}

		protected abstract void UpdateCore(UpdateContext context);
	}
}
